package com.myFwk.config.swagger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Arrays;
import java.util.List;

/**
 * @Title:
 * @Description:
 * @Author: guowl
 * @version： 1.0
 * @Date:2021/8/30
 * @Copyright: Copyright(c)2021 RedaFlight.com All Rights Reserved
 */
@Configuration
@EnableSwagger2
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerAutoConfiguration {

    @Autowired
    private SwaggerProperties swaggerProperties;

    /**
     * 信息简介
     *
     * @return
     */
    @Bean
    public Docket docket() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()) //介绍接口的一些信息
                .select()
                .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))//为那些接口生成swarg文档
                .paths(PathSelectors.any())
                .build();
//        安全配置
        docket.securitySchemes(securityScheme())  //安全规则
                .securityContexts(securityContexts());//安全配置的上下文
        return docket;
    }

    private List<SecurityContext> securityContexts() {
        return Arrays.asList(new SecurityContext(Arrays.asList(new SecurityReference("Authorization",
                new AuthorizationScope[]{new AuthorizationScope("global", "accessResource")})),
                PathSelectors.any()));
    }

    /**
     * 安全生成规则
     *
     * @return
     */
    private List<SecurityScheme> securityScheme() {
        return Arrays.asList(new ApiKey("Authorization", "Authorization", "Authorization"));
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().contact(new Contact(swaggerProperties.getName(), swaggerProperties.getUrl(), swaggerProperties.getEmail()))
                .title(swaggerProperties.getTitle())
                .description(swaggerProperties.getDescription())
                .version(swaggerProperties.getVersion())
                .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
                .build();
    }


}
